using ServiceStack.Commands;
using ServiceStack.Support;
using System;
using System.Collections.Generic;
using System.Threading;
namespace ServiceStack
{
	public class CommandsUtils
	{
		public static List<T> ExecuteAsyncCommandList<T>(TimeSpan timeout, params ICommandList<T>[] commands)
		{
			return CommandsUtils.ExecuteAsyncCommandList<T>(timeout, commands);
		}
		public static List<T> ExecuteAsyncCommandList<T>(TimeSpan timeout, IEnumerable<ICommandList<T>> commands)
		{
			List<T> list = new List<T>();
			List<WaitHandle> list2 = new List<WaitHandle>();
			foreach (ICommandList<T> current in commands)
			{
				AutoResetEvent autoResetEvent = new AutoResetEvent(false);
				list2.Add(autoResetEvent);
				CommandResultsHandler<T> state = new CommandResultsHandler<T>(list, current, autoResetEvent);
				ThreadPool.QueueUserWorkItem(new WaitCallback(CommandsUtils.ExecuteCommandList), state);
			}
			CommandsUtils.WaitAll(list2.ToArray(), timeout);
			return list;
		}
		public static void WaitAll(WaitHandle[] waitHandles, TimeSpan timeout)
		{
			if (waitHandles != null && waitHandles.Length != 0)
			{
				if (Thread.CurrentThread.GetApartmentState() == ApartmentState.STA)
				{
					for (int i = 0; i < waitHandles.Length; i++)
					{
						waitHandles[i].WaitOne(timeout, false);
					}
					return;
				}
				if (!WaitHandle.WaitAll(waitHandles, timeout, false))
				{
					throw new TimeoutException();
				}
			}
		}
		private static void ExecuteCommandList(object state)
		{
			((ICommandExec)state).Execute();
		}
		private static void ExecuteCommandExec(object state)
		{
			((ICommandExec)state).Execute();
		}
		public static void ExecuteAsyncCommandExec(TimeSpan timeout, IEnumerable<ICommandExec> commands)
		{
			foreach (ICommandExec current in commands)
			{
				ThreadPool.QueueUserWorkItem(new WaitCallback(CommandsUtils.ExecuteCommandExec), current);
			}
		}
		public static List<WaitHandle> ExecuteAsyncCommandExec(IEnumerable<ICommandExec> commands)
		{
			List<WaitHandle> list = new List<WaitHandle>();
			foreach (ICommandExec arg_24_0 in commands)
			{
				AutoResetEvent autoResetEvent = new AutoResetEvent(false);
				list.Add(autoResetEvent);
				CommandExecsHandler state = new CommandExecsHandler(arg_24_0, autoResetEvent);
				ThreadPool.QueueUserWorkItem(new WaitCallback(CommandsUtils.ExecuteCommandList), state);
			}
			return list;
		}
	}
}
